package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询每页菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Long page,Long pageSize,String name) {
        Page<Dish> objectPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //查询页面数据
        dishService.page(objectPage,new LambdaQueryWrapper<Dish>().like(name!=null,Dish::getName,name));
        //拷贝page对象至dishDtoPage
        BeanUtils.copyProperties(objectPage,dishDtoPage,"records");
        //获取菜品数据列表
        List<Dish> records = objectPage.getRecords();
        //转换菜品Dish为DishDto
        List<DishDto> list = records.stream().map(item->{
            DishDto dishDto = new DishDto();
            //将菜品属性拷贝
            BeanUtils.copyProperties(item,dishDto);
            //根据菜品分类id获取分类名
            Category category = categoryService.getById(item.getCategoryId());
            //设置分类名
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> dish(@RequestBody DishDto dishDto) {
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功");
    }

    /**
     * 回显菜品数据
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> getdish(@PathVariable Long id) {
        DishDto dishDto = dishService.queryWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> editDish(@RequestBody DishDto dishDto) {
        //清理所有菜品的缓存数据
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        //清理某个分类下面的菜品缓存数据,其他具体清理牵涉到修改状态等不使用，直接全部
        String key = "dish_"+dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        log.info(dishDto.toString());
        dishService.editWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 修改菜单状态
     * @param ids
     * @param status
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(String ids,@PathVariable String status) {

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);

        //获取需要改变状态id
        //String ids = request.getParameter("ids");
        //根据要改变状态的id改变状态
        for (String id : ids.split(",")) {
            dishService.update(new LambdaUpdateWrapper<Dish>().eq(Dish::getId,id).set(Dish::getStatus,status));
        }
        return R.success("修改状态成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(String ids) {
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //根据id删除
        dishService.deleteWithFlavor(ids);
        return R.success("删除成功");
    }

    /**
     * 套餐回显商品
     * @param dish
     * @return
     */
    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtos = null;
        //构建redis缓存菜单字段
        String key = "dish_"+dish.getCategoryId()+"_"+1;
        //从redis缓存获取菜品数据
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }
        //根据套餐id查询菜品
        List<Dish> dishes = dishService.list(new LambdaQueryWrapper<Dish>()
                .eq(dish.getCategoryId()!=null,Dish::getCategoryId, dish.getCategoryId())
                .orderByDesc(Dish::getUpdateTime).eq(Dish::getStatus,1));
        dishDtos = dishes.stream().map(item->{
            /*DishDto dishDto = new DishDto();
            //赋值菜品信息
            BeanUtils.copyProperties(item,dishDto);
            //插入所属套餐名
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>()
                    .eq(Category::getId, dish.getCategoryId()));
            dishDto.setCategoryName(category.getName());
            //插入口味信息
            //DishDto di = dishService.queryWithFlavor(dish.getId());*/

            //这里我直接使用之前显示口味和菜品的Service方法
            DishDto dishDto = dishService.queryWithFlavor(item.getId());
            //插入所属套餐名
            Category category = categoryService.getOne(new LambdaQueryWrapper<Category>()
                    .eq(Category::getId, dish.getCategoryId()));
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());
        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);
        return R.success(dishDtos);
    }
}
